import asyncio
from utils import os

class Time:
	def	__init__(self, timepoint) -> None:
		if isinstance(timepoint, str):
			split = list(map(int, timepoint.split(":")))
			split = [0]*(3 - len(split)) + split
			self.split = split + [0]
			timepoint = split[0] * 60 * 60 + split[1] * 60 + split[2]

		self.time = int(timepoint * 1000)
		self.split = (
			int(timepoint / (1000 * 60 * 60)),
			int(timepoint / (1000*60)) % 60,
			int(timepoint / 1000) % 60,
			int(timepoint % 1000)
		)

	def __str__(self) -> str:
		h, m, s, ms = self.split
		return f"{h}:{m}:{s}.{ms}"

	def __add__(self, other):
		if isinstance(other, Time):
			return Time(self.time + other.time)
		return Time(self.time + other)

	def __sub__(self, other):
		if isinstance(other, Time):
			return Time(self.time - other.time)
		return Time(self.time - other)

	def __lt__(self, other):
		if isinstance(other, Time):
			return self.time < other.time
		return self.time < other

	def __gt__(self, other):
		if isinstance(other, Time):
			return self.time > other.time
		return self.time > other


async def slice(path, filename, intervals: list, margin: int=0):
	tasks = []
	for interval in intervals:
		start = Time(interval["start"]) + margin / 2
		if start.time < 0:
			start = Time(0)

		end = Time(interval["end"]) - margin / 2
		title = interval["title"]

		command = f'ffmpeg -ss {start} -to {end} -i "{path}/{filename}" -qscale 0 "{path}/{title}.mp3"'
		task = asyncio.create_task(os.system(command))
		tasks.append(task)

	await asyncio.gather(*tasks)
